package server;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;


import Messages.Message;
import Utility.ClientUtilities;
import Utility.FileUtilities;
import Utility.PaxosMessageReader;
import Utility.SocketReaderWriter;
import Utility.Host;

/**
 * Server that acts as : (PAXOS SERVER)
 * 
 *  1. PROPOSER - Proposes request (N,V)
 *  2. ACCEPTOR - Accepts the proposal request
 *  3. LEARNER - Learns the accepted proposals
 *
 */
public class Server4{
	Socket clientSocket;
	ServerSocket serverSocket;
	int serverId = 4;
	//static boolean[] locks_Array;
	
	public static void main(String args[]) throws IOException,ClassNotFoundException {
		Server4 serverSide = new Server4();
		serverSide.startServer();
	}

	/**
	 * Method to start the server
	 * 
	 * @throws IOException
	 * @throws ClassNotFoundException
	 */

	public void startServer() throws IOException, ClassNotFoundException {
		Host server4 = ClientUtilities.serversMap.get(4);
		File f = new File(System.getProperty("user.dir")+File.separator+"locksfile"+serverId);
		if(f.exists()){
				f.delete();
		}
		
		try {
			System.out.println("[SERVER-4] Listening for clients with host : " + server4.getHostName() + " using Port : " + server4.getPortNumber() );
			serverSocket = new ServerSocket(Integer.parseInt(server4.getPortNumber()));
		} catch (IOException e) {
			System.out.println("Could not find connection");
			e.printStackTrace();
		}
		try {
			// Run this server until  it get killed manually. 
			// This keeps accepting client connections and spawns a new thread to take over task.
			while(true){
				clientSocket = serverSocket.accept();
				System.out.println(clientSocket);
				System.out.println(this.getClass().getSimpleName() + " Accepted client connection from host : " + clientSocket.getInetAddress().getHostAddress());	
				PaxosServerThread paxosServerThread = new PaxosServerThread(clientSocket,serverId,true);
				Thread paxosThread = new Thread(paxosServerThread);
				paxosThread.start();
			}
		} catch (Exception e) {
			System.out.println("Accept failed");
			e.printStackTrace();
		}
		System.out.println("[SERVER-4] Making i/o connections :) ");
	}
}
